#include "TextNode.h"
#include "..\renderer\VertexDeclaration.h"
#include "..\content\BitmapFont.h"

namespace ds {

TextNode::TextNode(const std::string& name,const std::string& materialName,const std::string& bitmapFont) : Node(name,materialName,true) , m_FontName(bitmapFont) {
	m_Buffer = new TransformedTexturedBuffer(2048,4096,true);
}

TextNode::~TextNode() {
}

void TextNode::rebuild() {
	m_Buffer->clear();
	float u1,u2,v1,v2;
	int ar[6] = {0,1,2,1,3,2};
	u1 = v1 = 0.0f;
	u2 = v2 = 1.0f;
	float x, y , z;
	float dimX,dimY;
	int idxOffset = 0;
	x = 10.0f;
	y = 10.0f;
	z = 1.0f;
	float padding = 0.0f;
	m_Total = 0;
	float scale = 1.0f;
	float texSize = (float)m_Font->getTextureSize();
	TextEntriesIterator it;
	for ( it = m_TextEntries.begin(); it != m_TextEntries.end();++it ) {
		if ( it->second.active ) {
			std::string text = it->second.text;
			x = it->second.pos.x;
			y = it->second.pos.y;
			padding = 0.0f;
			scale = it->second.scale;
			for ( size_t cnt = 0; cnt < text.length(); ++cnt ) {
				char c = text[cnt];
				CharDef cd = m_Font->getCharDef(c);
				x += padding;
				padding = (cd.width+2)  * scale;
				u1 = (float)cd.startX/texSize;
				v1 = (float)cd.startY/texSize;
				u2 = u1 + (float)cd.width/texSize;
				v2 = v1 + (float)m_Font->getCharHeight()/texSize;

				dimX = cd.width * scale;
				dimY = m_Font->getCharHeight() * scale;

				m_Buffer->add(TransformedTexturedVertex(x ,y , z, u1, v1));
				m_Buffer->add(TransformedTexturedVertex(x + dimX , y , z, u2, v1));
				m_Buffer->add(TransformedTexturedVertex(x , y + dimY , z, u1, v2));
				m_Buffer->add(TransformedTexturedVertex(x + dimX , y + dimY , z, u2, v2));
		
				// create indices	
				for ( int i = 0; i < 6; ++i ) {
					m_Buffer->addIndex(ar[i]+idxOffset);
				}
				idxOffset += 4;
				m_Total += 2;
			}
		}
	}
	m_Buffer->update();
}

void TextNode::prepareRendering() {	
	rebuild();
	m_Buffer->prepareData();
}

void TextNode::draw() {
	m_Buffer->render(m_Total);
}

};
